package com.tsingteng.cosfun.base;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;


import com.tsingteng.cosfun.widget.dialog.ContentDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述:
 * 创建人: 肖利
 * 时间: 2018/8/13
 * qq: (872179966)
 */

public class PermissionActivity extends AppCompatActivity {
    private static final int MY_PERMISSIONS_REQUEST = 1001;
    private IPermission mPermissionAction;
    private String mPermissionDescription;
    private List<String> needPermissions = null; // 未获得的权限列表

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
    }



    /**
     * 动态请求权限
     * @param permissions
     * @param action
     * @param needPermissionDescription
     */
    public void requestPermission(String[] permissions, IPermission action, String needPermissionDescription) {

        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                if (needPermissions == null)
                    needPermissions = new ArrayList<>();
                needPermissions.add(permission);
            }
        }
        if (needPermissions == null) {  // 已经获得权限，直接执行
            action.callAll();
            return;
        }
        boolean needRationale = false; // 是否需要权限的原因。当申请的权限被用户拒绝之后，再次申请时会提示
        for (String p : needPermissions) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, p)) {
                needRationale = true;
                break;
            }
        }

        mPermissionAction = action;  // 获得权限之后的回调
        mPermissionDescription = needPermissionDescription;  // 申请权限的描述信息

        if (needRationale) { // 提示之后申请权限
            new ContentDialog(this).setContent("权限申请").setAffirmContent("确认").setOnOneClickListener(new ContentDialog.OnOneClickListener() {
                @Override
                public void onAffirm() {
                    ActivityCompat.requestPermissions(PermissionActivity.this,
                            needPermissions.toArray(new String[0]),
                            MY_PERMISSIONS_REQUEST);
                }
            }).show();
        } else {
            ActivityCompat.requestPermissions(this,
                    needPermissions.toArray(new String[0]),
                    MY_PERMISSIONS_REQUEST);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_REQUEST) {
            boolean allGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                }
            }
            if (allGranted) {  // 已获得全部权限
                mPermissionAction.callAll();
            } else {  // 未获得权限，提示是否打开设置页面
                new ContentDialog(this).setContent("权限申请失败,是否前往设置").setAffirmContent("确定").setCancelContent("稍后").setOnTwoClickListener(new ContentDialog.OnTwoClickListener() {
                    @Override
                    public void onAffirm() {
                        startAppSettings();
                    }

                    @Override
                    public void onCancel() {

                    }
                }).show();
                return;
            }
        }
    }

    private static final String PACKAGE_URL_SCHEME = "package:"; // 方案
    private static final int REQUEST_CODE_REQUEST_SETTING = 1027;

    /**
     * 前往设置权限
     */
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse(PACKAGE_URL_SCHEME + this.getPackageName()));
        this.startActivityForResult(intent, REQUEST_CODE_REQUEST_SETTING);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_REQUEST_SETTING) {
            List<String> list = new ArrayList<>();
            for (String permission : needPermissions) {
                if (ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_DENIED) {
                    list.add(permission);
                }
            }
            if (list.size() > 0) {
                onRequestPermissionFailed(list.toArray(new String[list.size()]));
            } else {
                mPermissionAction.callAll();
            }
        }
    }

    /**
     * 未获取到的权限回调
     *
     * @param permissions 未获取到的权限列表
     */
    protected void onRequestPermissionFailed(String[] permissions) {

    }
}
